package com.zjmcollege.hotpot.search.controller;

import com.zjmcollege.hotpot.search.model.SearchResultModel;
import com.zjmcollege.hotpot.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief
 * @email 122162005@qq.com
 * @date 2019-11-07 22:15
 */
@Controller
@RequestMapping("/s")
public class SearchController {
    @Autowired
    private SearchService searchService;
    @GetMapping
    public String query(@RequestParam(required = false, defaultValue = "") String wd,
                        @RequestParam(required = false, defaultValue = "1") int page,
                        @RequestParam(name = "page_size",required = false,
                                defaultValue = "10") int pageSize,
                        Model model) {
        // 传入搜索关键词为空则跳转到首页
        if ("".equals(wd)) {
            return "redirect: /";
        }

        Page<SearchResultModel> results = searchService.search(wd, page, pageSize);

        model.addAttribute("wd", wd);
        model.addAttribute("results", results);
        return "search/result";
    }

    /**
     * 对搜索结果进行投票
     * 赞同，返回
     * @param type 投票类型
     * @param id
     * @return
     */
    @PostMapping("/{type}/{id}")
    @ResponseBody
    public SearchResultModel vote(@PathVariable String type,
                                  @PathVariable String id) {
        if ("s".equals(type)) {
            return searchService.updateSupport(id);
        } else if ("o".equals(type)) {
            return searchService.updateOppose(id);
        }

        return null;
    }
}
